package com.campus.service.impl;

import com.campus.dao.CourseLearnUnitDao;
import com.campus.model.CourseLearnUnit;
import com.campus.model.UnitCompletion;
import com.campus.service.CourseLearnUnitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class CourseLearnUnitServiceImpl implements CourseLearnUnitService {

    @Autowired
    private CourseLearnUnitDao courseLearnUnitDao;

    @Override
    public boolean createCourseLearnUnitWithStudents(CourseLearnUnit unit) {
        // 1. 创建课程单元
        int unitId = courseLearnUnitDao.createCourseLearnUnit(unit);
        if (unitId <= 0) {
            return false;
        }

        // 2. 获取班级 ID
        Integer classId = courseLearnUnitDao.getClassIdByCourseId(unit.getCourseId());
        if (classId == null) {
            return false;
        }

        // 3. 获取班级中所有学生 ID
        List<Integer> studentInClassIds = courseLearnUnitDao.getStudentInClassIdsByClassId(classId);
        if (studentInClassIds.isEmpty()) {
            return false;
        }

        // 4. 批量插入学生学习记录
        int studentsLinked = courseLearnUnitDao.insertStudentLearningBatch(unitId, studentInClassIds);
        return studentsLinked == studentInClassIds.size();
    }

    @Override
    public boolean deleteCourseLearnUnit(int unitId) {
        return courseLearnUnitDao.deleteCourseLearnUnit(unitId) > 0;
    }

    @Override
    public boolean updateCourseLearnUnit(CourseLearnUnit unit) {
        return courseLearnUnitDao.updateCourseLearnUnit(unit) > 0;
    }

    @Override
    public List<CourseLearnUnit> listAllCourseLearnUnits() {
        return courseLearnUnitDao.listAllCourseLearnUnits();
    }

    @Override
    public List<UnitCompletion> getAllUnitsCompletion() {
        // 从 DAO 获取所有学习单元的完成度
        return courseLearnUnitDao.getAllUnitsCompletion();
    }

}
